import React, { Component, createRef } from 'react';
import { Form, Input, Button, message } from 'antd';
import { KeyOutlined, TabletOutlined, FieldNumberOutlined } from '@ant-design/icons';
import Captcha from "../../components/Captcha"
import url from "../../config/url"
import req from "../../http/req"
import { withRouter } from "react-router-dom"
class Mobilelogin extends Component {
  state = {
    time: 10,        // 倒计时的时间长度
    sentCode: false, // 标志是否已经完成短信的获取【算是性能优化，如果没有获取过短信，那么肯定不能发送ajax请求后盾验证】
    enabled: true,  //
  }
  constructor(props) {
    super(props)
    this.capRef = createRef()
    this.formRef = createRef()
  }
  render() {
    return (
      <Form
        ref={this.formRef}
        name="normal_login"
        className="login-form"
        initialValues={{}}
        onFinish={this.onFinish}
      >
        <Form.Item
          name="mobile"
          maxLength="11"
          rules={[{ required: true, message: '请输入手机号!' }]}
        >
          <Input prefix={<TabletOutlined className="site-form-item-icon" />} placeholder="手机号" />
        </Form.Item>
        <Form.Item
          name="captcha"
          rules={[{ required: true, message: '请输入图形验证码!' }]}
        >
          <div>
            <Input
              prefix={<KeyOutlined className="site-form-item-icon" />}
              type="text"
              placeholder="请输入图形验证码"
              style={{ width: "70%", marginRight: "9px" }}
            />
            <Captcha h={32} w={96} setKey={this.getKey} />
          </div>
        </Form.Item>
        <Form.Item
          name="code"
          rules={[{ required: true, message: '请输入短信验证码!' }]}
        >
          <div>
            <Input
              prefix={<FieldNumberOutlined className="site-form-item-icon" />}
              type="text"
              maxLength="6"
              style={{ width: "70%", marginRight: "70px" }}
              placeholder="请输入短信验证码"
              style={{ width: "60%", marginRight: "9px" }}
            />
            <Button type="primary" onClick={this.SendCode} disabled={!this.state.enabled} style={{ width: "36%" }}>
              {this.state.enabled ? "获取短信" : `重新获取(${this.state.time})`}
            </Button>
          </div>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button" block disabled={!this.state.sentCode}>
            登录
          </Button>
        </Form.Item>
      </Form>
    );
  }
  // 提交处理
  onFinish = (values) => {
    // 取出需要的数据
    let { code, mobile } = values
    let params = { mobile, code, requestId: this.state.requestId }
    req.post(url.MobileLogin, params).then((res) => {
      if (res.data.errNo === 0) {
        message.success("登录成功", 2, () => {
          this.props.history.push("/dashboard")
        })
      }
    })
  };
  getKey = (key) => {
    this.setState({
      key
    })
  }
  SendCode = () => {
    // 问题：倒计时什么时候开始
    //  1。验证图形验证码  2.发送短信  3.（开始倒计时）
    // 解构出来的数据，有值就是值，没值就是undefined
    let { mobile, captcha } = this.formRef.current.getFieldsValue()
    if (/^1[3-9]\d{9}$/.test(mobile) && captcha) {
      // 数据基本没啥问题， 发送图形验证码的请求
      req.post(url.VerifyCaptcha, { key: this.state.key, captcha }).then((res) => {
        // console.log(res);
        if (res.data.errNo === 0) {
          let token = res.data.context.token
          req.post(url.SendCode, {
            mobile, token, type: 0
          }).then((ret) => {
            if (ret.data.errNo === 0) {
              this.setState({
                requestId: ret.data.requestId,
                sentCode: true
              })
              message.success("已发短信送验证码", 2)
              this.timedown()
            } else {
              message.error(res.data.errText, 2, () => {
                this.capRef.current.loadCaptcha()
              })
            }
          })
        } else {
          // 验证码失效
          message.error(res.data.errText, 2, () => {
            this.capRef.current.loadCaptcha()
          })
        }
      })
    } else {
      // 有问题，不能继续（调起表单的错误提示）
      message.error("请输入合法的手机号和图形验证码")
    }
    // console.log(mobile, captcha);
  }

  // 倒计时
  timedown = () => {
    if (this.state.time === 0) {
      // 倒计时已经结束
      this.setState({
        time: 10,         //  时间重置
        enabled: true     //  按钮可以被点击
      })
    } else {
      this.setState({
        time: this.state.time - 1,
        enabled: false
      })
      setTimeout(() => {
        this.timedown();
      }, 1000)
    }
  }
}




export default withRouter(Mobilelogin);
